<?php
namespace api\modules\v1\models;
use api\common\controllers\CommonController;
use Yii;
use api\common\models\Common;
use yii\web\HttpException;
use api\func\func;
use \yii\db\Query;
use yii\data\Pagination;
use yii\web\NotFoundHttpException;
use api\common\models\Mar;
use \yii\caching\FileDependency;
/**
 * Login form
 */
class Publish extends Common
{

    public $img;

    public $badword='';

    public static function tableName()
    {
        return '{{%article_app}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required', 'on' => ['publish','edit']],
            [['title'], 'validateTitle', 'on' => ['publish','edit']],
            [['title'], 'string', 'min' => 5,'max'=>30,'on' => ['publish','edit']],
            [['title'], 'unique','message'=>'文章标题已存在', 'on' => ['publish']],

            [['content'], 'required', 'on' => ['publish','edit']],
            [['content'], 'validateContent', 'on' => ['publish','edit']],
            [['content'], 'getCoverImg', 'on' => ['publish','edit']],
            [['content'], 'string', 'min' => 10,'max'=>5000,'on' => ['publish','edit']],

            [['id'], 'required', 'on' => ['edit']],
            [['id'], 'integer', 'on' => ['edit']],

            [['status'], 'required', 'on' => ['publish','edit']],
            [['status'],'in', 'range' => [0,1], 'on' => ['publish','edit']],

            [['status'], 'integer', 'on' => ['search']],
            [['img'], 'required', 'on' => ['img']],
            [['img'], 'validateImg', 'on' => ['img']],

            [['catid'], 'integer', 'on' => ['publish','edit']],
        ];
    }


    public function attributeLabels()
    {
        return [
            'title' => Yii::t('app', '标题'),
            'content' => Yii::t('app', '内容'),
            'status' => Yii::t('app', '发布状态'),
        ];
    }

    /*
     * 验证文章标题
     * @param $attribute
     * @param $params
     */
    public function validateTitle($attribute, $params){

        if(func::safe_sql($this->title)){
            //throw new HttpException(401,'请勿提交非法参数',0);
        }
        $this->title= func::filterEmoji($this->title,'标题');
        $this->title= func::safe_filter($this->title);

        $this->badword($this->title,'标题');

        return true;
    }

    /*
     * 验证文章内容
     * @param $attribute
     * @param $params
     */
    public function validateContent($attribute, $params){
        if(func::safe_sql($this->content)){
            //throw new HttpException(401,'请勿提交非法参数',0);
        }
        $this->content= func::filterEmoji($this->content,'内容');
        $this->content= func::safe_filter($this->content);

        $this->badword($this->content,'内容');

        $this->content = str_replace('<p></p>','<p>&nbsp;</p>',$this->content);

        return true;
    }

    /*
     * 获取封面图
     * @param $attribute
     * @param $params
     */
    public function getCoverImg($attribute, $params){
        preg_match_all('/<img.+src=[\"\'](.+\.(jpg|gif|bmp|bnp|png|jpeg))[\"\']/iU',$this->content,$matches);
        $result= $matches[1];
        $data = [];
        $this->cover_img = '';
        $count = count($result);
        if($count == 0) return true;
        if($count >= 3){ //取三张图
            $data[] = $result[0];
            $data[] = $result[1];
            $data[] = $result[2];
        }else{ //取一张图
            $data[] = $result[0];
        }
        $this->cover_img = implode(',',$data);
        return true;
    }



    /*
     * 图片上传
     * @return null
     */
    public function img(){
        if ($this->validate()) {
            return $this->img;
        }
        return null;
    }

    public function news(){

        if(Yii::$app->user->identity->is_authpublish !=1){
            throw new HttpException(401,'您没有发布权限',0);
        }

        if($data = self::findOne(['title'=>$this->title])){
            throw new HttpException(401,'该标题文章已经存在!',0);
        }


        if ($this->validate()) {
            $this->author = Yii::$app->user->identity->id;
            $this->pubdate = date('Y-m-d H:i:s');
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }

    public function edit(){
        if(Yii::$app->user->identity->is_authpublish !=1){
            throw new HttpException(401,'您没有发布权限',0);
        }

        if(self::find()->where('title = "'.$this->title .'" and id !='.$this->id)->one()){
            throw new HttpException(401,'该标题文章已经存在!',0);
        }

        $data = self::findOne(['id'=>$this->id]);

        if($data['author'] != Yii::$app->user->identity->id){
            throw new HttpException(401,'请勿非法提数据!',0);
        }

        if(in_array($data['status'],[1,2])){
            throw new HttpException(401,'该发布状态下不允许修改!',0);
        }

        if ($this->validate()) {
            if ($this->save(false)) {
                return true;
            }
        }
        return null;
    }

    /*
     * 敏感词屏蔽
     */
    public function badword($str,$type){
        //敏感词过滤
        $cahce = Yii::$app->cache;
        $cacheKey = 'comment_badword';
        $badword = $cahce->get($cacheKey);
        if ($badword === false) {
            $badword_model = new Mar('{{%badword}}');
            $badword = $badword_model->find()->where('1 = 1')->asArray()->all();
            foreach($badword as $key=>$val){
                $badword[$key]['badword'] = trim($val['badword'],PHP_EOL);
            }
            $cahce->set($cacheKey, $badword,Yii::$app->params['cache_time_comment_badword'],new FileDependency(['fileName' => 'cache.txt']));
        }

        foreach($badword as $value){
            if($value['use_range'] != 2){
                $value['badword'] = trim($value['badword']);
                if(strpos($str,$value['badword']) !== false){
                    throw new HttpException(401,$type.'中有敏感字符【'.$value['badword'].'】',0);
                }
            }
        }

       /* if(!is_array($this->badword)){
            $data = ((new Query())
                ->select('badword')
                ->from('{{%badword}}')
                ->all()
            );
            $data = array_column($data,'badword');
        }else{
            $data = $this->badword;
        }
        foreach($data as $value){
            $value = trim($value);
            if(strpos($str,$value) !== false){
                throw new HttpException(401,'您发布的内容有敏感字符【'.$value.'】，请修改后再次尝试!',0);
            }
        }*/
        return true;
    }

    public function del($id){
        $id = (int)$id;
        if(!$data = self::findOne(['id'=>$id,'author'=>Yii::$app->user->identity->id])){
            throw new HttpException(401,'未找到有关信息!',0);
        }
        if(in_array($data['status'],[1,2])){
            throw new HttpException(401,'此状态下不可删除!',0);
        }
        if(self::deleteAll(['id'=>$id,'author'=>Yii::$app->user->identity->id])){
            return true;
        }
        return null;
    }

    /*
     * 图片base64解码并本地化
     * @param $attribute
     * @param $params
     * @return bool
     */
    public function validateImg($attribute, $params){
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $this->img, $result)){
            $type = $result[2];
            $file_name = './uploads/publish_img/'.uniqid(Yii::$app->user->identity->id.'_').'.'.$type;
            if (file_put_contents($file_name, base64_decode(str_replace($result[1], '', $this->img)))){
                $this->img = self::ftp_upload(substr($file_name,1),$file_name,1);
                return true;
            }
        }else{
            $this->addError($attribute, '图片解析失败');
            return false;
        }
    }





    public function search($params){
        $fields = 'id,title,pubdate,status,cover_img';
        $where = 'author = '.Yii::$app->user->identity->id;
        if(isset($params['status']) && !empty($params['status'])){
            $status = (int)$params['status'];
            $where .= " and `status` = ".$status;
        }
        if(isset($params['title']) && !empty($params['title'])){
            $title = $params['title'];
            if(func::safe_sql($title)){
                throw new HttpException(401,'请勿提交非法参数',0);
            }
            $title=strtr($title,array('%'=>'\%', '_'=>'\_', '\\'=>'\\\\', '\''=>'\\\''));
            $title= func::safe_filter($title);
            $where .= " and title like '%".$title."%'";
        }

        $query = (new Query())->from(self::tableName())->select($fields)->where($where);
        $query->orderBy('pubdate desc');
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];
        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        //echo $query->offset($pagination->offset)
        //    ->limit($pagination->limit)->createCommand()->getRawSql();exit;

        foreach($data as &$value){
            $zst = [];
            if($value['cover_img'] != ''){
                $zst = explode(',',$value['cover_img']);
            }
            unset($value['cover_img']);
            $value['zst'] = $zst;
        }

        $this->serializePagination($pagination);
        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;
        return $_data;
    }

    /*
     * 获取详情
     */
    public function getInfo($params){
        $id = (int)$params['id'];
        $fields = 'id,title,content,cover_img,pubdate,status';
        if($data = self::find()->select($fields)->where(['author'=>Yii::$app->user->identity->id,'id'=>$id])->asArray()->one()){
            return $data;
        }else{
            throw new NotFoundHttpException('未找到该文章');
        }
    }

    /*
     * 文章统计
     */
    public function statistic(){
        $uid = Yii::$app->user->identity->id;
        $_data = (new Query())->select(['`status`','count(*) as count'])->where(['author'=>$uid])->from(self::tableName())->groupBy(['status'])->all();
        $data = [];
        if(count($_data) >0 ){
            foreach($_data as $value){
                $data[] = ['status'=>$value['status'],'count'=>$value['count']];
            }
        }
        return $data;
    }

}
